package com.client.job.runLogs;

/**
 * Logs线程池
 *
 * @author mnengxiangzhong
 * @version 1.0
 * @date 2021/9/24/024
 */


import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;



/**
 * 线程池代理类
 *
 * @author monxz
 * @param <T>
 * @Date  2020年11月17日下午3:05:25
 * @Des
 *
 */
public class LogsThreadPoolProxy<T> {
    ThreadPoolExecutor mThreadPoolExecutor;

    private int corePoolSize = 5;
    private int maximumPoolSize = 10;
    private long keepAliveTime = 10L;

    public LogsThreadPoolProxy() {
    }

    protected ThreadPoolExecutor initExecutor() {
        if(mThreadPoolExecutor == null) {
            synchronized(LogsThreadPoolProxy.class) {
                if(mThreadPoolExecutor == null) {

                    TimeUnit unit =  TimeUnit.MILLISECONDS;
                    ThreadFactory threadFactory = Executors.defaultThreadFactory();
                    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
                    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();

                    mThreadPoolExecutor = new ThreadPoolExecutor(
                            corePoolSize,//核心线程数
                            maximumPoolSize,//最大线程数
                            keepAliveTime,//保持时间
                            unit,//保持时间对应的单位
                            workQueue,
                            threadFactory,//线程工厂
                            handler);//异常捕获器
                }
            }
        }
        return mThreadPoolExecutor;
    }



    /**执行任务*/
    public void executeTask(Runnable r) {
        initExecutor();
        mThreadPoolExecutor.execute(r);
    }


    /**提交任务*/
    public Future<?> commitTask(Runnable r) {
        initExecutor();
        return mThreadPoolExecutor.submit(r);
    }

    /**提交任务*/
    public Future<?> commitTask(Callable<T> r) {
        initExecutor();
        return mThreadPoolExecutor.submit(r);
    }

    /**提交任务*/
    public List<Future<T>>   commitTaskList(List<Callable<T>> list) {
        initExecutor();
        try {
            return mThreadPoolExecutor.invokeAll(list);
        } catch (InterruptedException e) {
            return null;
        }

    }

    /**删除任务*/
    public void removeTask(Runnable r) {
        initExecutor();
        mThreadPoolExecutor.remove(r);
    }



}
